<?php

namespace Places;

use Nette\Application\UI\Control;
use Nette\Forms\Form;
use Src\GpsPickerExtension;

class PlacesForm extends Control
{
	public function setValues($values)
	{
		$this->getComponent('form')->setDefaults($values);

		return $this;
	}

	/**
	 * Form control
	 *
	 * @return Nette\Application\UI\Form;
	 */
	protected function createComponentForm()
	{

		$form = new Form;

		$form->addText('name', 'Jméno:')
			 ->addRule(Form::MIN_LENGTH, 'min. %d znaky', 3);

		$form->addText('coord', 'GPS:');

		$form->addText('street', 'Ulice a č.p.:')
			 ->addCondition(Form::FILLED)
			 	->addRule(Form::PATTERN, 'neplatné zadání', '(.*[^0-9]+) (([1-9][0-9]*)/)?([1-9][0-9]*[a-cA-C]?)');;
		$form->addText('city', 'Město:')
			 ->addCondition(Form::FILLED)
			 	->addRule(Form::MIN_LENGTH, 'min. %d znaky', 2);
		$form->addText('zip', 'PSČ:')
			 ->addCondition(Form::FILLED)
		 		->addRule(Form::PATTERN, 'má 5 číslic', '([0-9]\s*){5}');
		$form->addTextarea('note', 'Poznámka:')
			 ->getControlPrototype()->class("texyla");

		if($this->presenter->getParam('id') > 0) {
			$form->addSubmit('save', 'Upravit')
				 ->setAttribute('class', 'btn btn-warning');
			$form->onSuccess[] = $this->update;
		} else {
			$form->addSubmit('save', 'Uložit')
				 ->setAttribute('class', 'btn btn-success');
			$form->onSuccess[] = $this->insert;
		}
		return $form;

	}

	/**
	 * Insert action form
	 *
	 * @param Nette\Application\UI\Form;
	 */
	public function insert(Form $form)
	{
		if($form->isSubmitted()) {
			$values = $form->getValues();
			$values->user = $this->presenter->getUser()->getId();

			$e = $this->presenter->context->places->insert($values);
			if($e instanceof DibiException) {
				return $form->addError('Error message insert');
			}

			$this->presenter->flashMessage('Místo bylo úspěšně přidáno.', 'success');
		}

		$this->presenter->redirect('Places:');
	}

	/**
	 * Update action form
	 *
	 * @param Nette\Application\UI\Form;
	 */
	public function update(Form $form)
	{
		if($form->isSubmitted()) {
			$values = $form->getValues();
			$id = $this->presenter->getParam('id');

			$e = $this->presenter->context->places->update($id, $values);
			if($e instanceof DibiException) {
				return $form->addError('Error message update');
			}

			$this->presenter->flashMessage('Místo bylo úspěšně upravno.', 'success');
		}

		$this->presenter->redirect('Places:');
	}

	/**
	 * render
	 *
	 */
	public function render()
	{
		$this->template->setFile(__DIR__ . '/placesForm.latte');
		$this->template->render();
	}
}